import torch
from torch import nn


class ConvLSTMCell(nn.Module):

    def __init__(self, input_dim, hidden_dim, kernel_size, bias):
        super(ConvLSTMCell, self).__init__()

        self.input_dim = input_dim
        self.hidden_dim = hidden_dim

        self.kernel_size = kernel_size
        self.padding = kernel_size[0] // 2, kernel_size[1] // 2
        self.bias = bias

        self.conv = nn.Conv2d(in_channels=self.input_dim + self.hidden_dim,
                              out_channels=4 * self.hidden_dim,
                              kernel_size=self.kernel_size,
                              padding=self.padding,
                              bias=self.bias)

    def forward(self, input_tensor, cur_state):
        h_cur, c_cur = cur_state

        combined = torch.cat([input_tensor, h_cur], dim=1)  # concatenate along channel axis

        combined_conv = self.conv(combined)
        cc_i, cc_f, cc_o, cc_g = torch.split(combined_conv, self.hidden_dim, dim=1)
        i = torch.sigmoid(cc_i)
        f = torch.sigmoid(cc_f)
        o = torch.sigmoid(cc_o)
        g = torch.tanh(cc_g)

        c_next = f * c_cur + i * g
        h_next = o * torch.tanh(c_next)

        return h_next, c_next

    def init_hidden(self, batch_size, image_size):
        height, width = image_size
        return (torch.zeros(batch_size, self.hidden_dim, height, width, device=self.conv.weight.device),
                torch.zeros(batch_size, self.hidden_dim, height, width, device=self.conv.weight.device))


class ConvLSTM(nn.Module):

    def __init__(self, input_dim, hidden_dim, kernel_size, num_layers,
                 batch_first=False, bias=True, return_all_layers=False):
        super(ConvLSTM, self).__init__()

        self._check_kernel_size_consistency(kernel_size)

        # Make sure that both `kernel_size` and `hidden_dim` are lists having len == num_layers
        kernel_size = self._extend_for_multilayer(kernel_size, num_layers)
        hidden_dim = self._extend_for_multilayer(hidden_dim, num_layers)
        if not len(kernel_size) == len(hidden_dim) == num_layers:
            raise ValueError('Inconsistent list length.')

        self.input_dim = input_dim
        self.hidden_dim = hidden_dim
        self.kernel_size = kernel_size
        self.num_layers = num_layers
        self.batch_first = batch_first
        self.bias = bias
        self.return_all_layers = return_all_layers

        cell_list = []
        for i in range(0, 1):
            cur_input_dim = self.input_dim if i == 0 else self.hidden_dim[i - 1]

            cell_list.append(ConvLSTMCell(input_dim=cur_input_dim,
                                          hidden_dim=self.hidden_dim[i],
                                          kernel_size=self.kernel_size[i],
                                          bias=self.bias))
        cell_list2 = []
        cell_list2.append(ConvLSTMCell(input_dim=24,
                                      hidden_dim=24,
                                      kernel_size=self.kernel_size[0],
                                      bias=self.bias))

        self.cell_list = nn.ModuleList(cell_list)

        self.cell_list2 = nn.ModuleList(cell_list2)

    def forward(self, input_tensor, hidden_state=None):
        if not self.batch_first:
            # (t, b, c, h, w) -> (b, t, c, h, w)
            input_tensor = input_tensor.permute(1, 0, 2, 3, 4)

        b, _, _, h, w = input_tensor.size()

        # Implement stateful ConvLSTM
        if hidden_state is not None:
            raise NotImplementedError()
        else:
            # Since the init is done in forward. Can send image size here
            hidden_state = self._init_hidden(batch_size=b,
                                             image_size=(h, w))

        layer_output_list = []
        last_state_list = []

        seq_len = input_tensor.size(1)
        cur_layer_input = input_tensor

        for layer_idx in range(self.num_layers):

            if layer_idx == 0:

                h, c = hidden_state[layer_idx]
                output_inner = []
                for t in range(seq_len):
                    h, c = self.cell_list[layer_idx](input_tensor=cur_layer_input[:, t, :, :, :],
                                                     cur_state=[h, c])
                    output_inner.append(h)

                layer_output = torch.stack(output_inner, dim=1)
                cur_layer_input = layer_output  #这里的下一层的输入被替换了

                layer_output_list.append(layer_output)
                last_state_list.append([h, c])

                # 将第一层lstm的结果output_inner修改成所需的形状
                processed_windows = []
                for i in range(14 - 8 + 1):  # 滑动窗口数量为7
                    # 提取当前窗口的8个张量
                    window = output_inner[i:i + 8]
                    # 沿通道维度拼接，得到形状 (8, 128, 50, 50)
                    combined = torch.cat(window, dim=1)
                    processed_windows.append(combined)
                # 沿新维度堆叠，得到形状 (8, 7, 128, 50, 50)
                cur_layer_input = torch.stack(processed_windows, dim=1)
            else:
                h_tcn, c_tcn = hidden_state[layer_idx]
                output_inner_tcn = []
                for t in range(7):
                    h_tcn, c_tcn = self.cell_list2[0](input_tensor=cur_layer_input[:, t, :, :, :],
                                                     cur_state=[h_tcn, c_tcn])
                    output_inner_tcn.append(h_tcn)
                layer_output_tcn = torch.stack(output_inner_tcn, dim=1)
                layer_output_list.append(layer_output_tcn)
                last_state_list.append([h_tcn, c_tcn])

        #插入

        if not self.return_all_layers:
            layer_output_list = layer_output_list[-1:]
            last_state_list = last_state_list[-1:]

        return layer_output_list, last_state_list

    def _init_hidden(self, batch_size, image_size):
        init_states = []
        for i in range(self.num_layers):
            if i ==0:
                init_states.append(self.cell_list[0].init_hidden(batch_size, image_size))
            else:
                init_states.append(self.cell_list2[0].init_hidden(batch_size, image_size))
        return init_states

    @staticmethod
    def _check_kernel_size_consistency(kernel_size):
        if not (isinstance(kernel_size, tuple) or
                (isinstance(kernel_size, list) and all([isinstance(elem, tuple) for elem in kernel_size]))):
            raise ValueError('`kernel_size` must be tuple or list of tuples')

    @staticmethod
    def _extend_for_multilayer(param, num_layers):
        if not isinstance(param, list):
            param = [param] * num_layers
        return param


if __name__ == '__main__':
    # 设置随机种子以确保可重复性
    torch.manual_seed(42)

    # 定义模型参数
    input_dim = 1  # 输入通道数
    hidden_dim = 3  # 隐藏层通道数
    kernel_size = (3, 3)  # 卷积核大小
    num_layers = 2  # LSTM层数
    batch_size = 8  # 批量大小
    seq_len = 14  # 序列长度
    height, width = 50, 50  # 图像高度和宽度

    # 创建 ConvLSTM 模型
    convlstm = ConvLSTM(input_dim=input_dim,
                        hidden_dim=hidden_dim,
                        kernel_size=kernel_size,
                        num_layers=num_layers,
                        batch_first=True,
                        bias=True,
                        return_all_layers=False)

    # 随机生成输入数据 (batch_size, seq_len, input_dim, height, width)
    input_tensor = torch.rand(batch_size, seq_len, input_dim, height, width)

    # 前向传播
    layer_output_list, last_state_list = convlstm(input_tensor)

    # 检查输出
    print("Output shape:", layer_output_list[0].shape)  # 应该输出 (batch_size, seq_len, hidden_dim, height, width)
    print("Last hidden state shape:", last_state_list[0][0].shape)  # 应该输出 (batch_size, hidden_dim, height, width)
    print("Last cell state shape:", last_state_list[0][1].shape)  # 应该输出 (batch_size, hidden_dim, height, width)
